<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>鼠标拖拽</title>
	<style type="text/css">
		#drag {
			width: 100px;
			height: 100px;
			background-color: red;
			position: absolute;
		}
	</style>
</head>
<body>
	<div id="drag"></div>
	<script type="text/javascript">
		window.onload = function () {
			var userAgent = navigator.userAgent,
			isMobile = userAgent.indexOf('iPhone') != -1 || userAgent.indexOf('Android') != -1;
			if (isMobile) {
				document.write('请用电脑');
				return;
			}
			var div = document.getElementById("drag");

			div.onmousedown = function (e) {
				var e = e || event;

				// 指针与窗口左边的距离 - div与窗口左边的偏移量 = 鼠标与div左边框的距离
				var distanceX = e.clientX - div.offsetLeft,	
					distanceY = e.clientY - div.offsetTop;
					// 将鼠标的移动事件注册到document上更好，因为注册到div上时当鼠标移动过快的时候就会脱离div，但是相关的事件来不及触发，就会出现bug。将鼠标移动事件注册到document上就不会出现这个事情
				document.onmousemove = function (e) {	
					var e = e || event;
					// 鼠标与屏幕左边的距离 - 鼠标与div左边框的距离 = div的偏移量
					div.style.left = e.clientX - distanceX + "px";
					div.style.top = e.clientY - distanceY + "px";
				}
				// 解绑事件
				document.onmouseup = function () {
					document.onmousemove = null;
					document.onmouseup = null;
				}

			}
		}
	</script>
</body>
</html>